﻿using System;

using System.Collections;
using RoughJs.Error;

namespace RoughJs.Ast
{
    /// <summary>
    /// 2010-01-5 ----- 2010-01-29
    /// 陈曦 1.0
    /// Microsoft Public License (Ms-PL)
    ///This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
    ///1. Definitions
    ///The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
    ///A "contribution" is the original software, or any additions or changes to the software.
    ///A "contributor" is any person that distributes its contribution under this license.
    ///"Licensed patents" are a contributor's patent claims that read directly on its contribution.
    ///2. Grant of Rights
    ///(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
    ///(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
    ///3. Conditions and Limitations
    ///(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
    ///(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
    ///(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
    ///(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
    ///(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
    /// </summary>
    public class NativeIterator : IdScriptableObject
    {
        private static Object ITERATOR_TAG = "Iterator";

        private const int
       Id_constructor = 1,
       Id_next = 2,
       Id___iterator__ = 3,
       MAX_PROTOTYPE_ID = 3;



        private Object objectIterator;


        public static String ITERATOR_PROPERTY_NAME = "__iterator__";

        public override String getClassName()
        {
            return "Iterator";
        }

        public static void init(ScriptableObject scope, bool sealed1)
        {

            NativeIterator iterator = new NativeIterator();
            iterator.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed1);


            NativeGenerator.init(scope, sealed1);


            NativeObject obj = new StopIteration();
            obj.setPrototype(getObjectPrototype(scope));
            obj.setParentScope(scope);
            if (sealed1) { obj.sealObject(); }
            ScriptableObject.defineProperty(scope, STOP_ITERATION, obj,
                                            ScriptableObject.DONTENUM);

            scope.associateValue(ITERATOR_TAG, obj);
        }
        private NativeIterator()
        {
        }

        private NativeIterator(Object objectIterator)
        {
            this.objectIterator = objectIterator;
        }


        public static Object getStopIterationObject(Scriptable scope)
        {
            Scriptable top = ScriptableObject.getTopLevelScope(scope);
            return ScriptableObject.getTopScopeValue(top, ITERATOR_TAG);
        }

        private static String STOP_ITERATION = "StopIteration";


        public class StopIteration : NativeObject
        {

            public override string getClassName()
            {
                return STOP_ITERATION;
            }

            public override bool hasInstance(Scriptable instance)
            {
                return instance is StopIteration;
            }

        }





        public override void initPrototypeId(int id)
        {
            String s;
            int arity;
            switch (id)
            {
                case Id_constructor: arity = 2; s = "constructor"; break;
                case Id_next: arity = 0; s = "next"; break;
                case Id___iterator__: arity = 1; s = ITERATOR_PROPERTY_NAME; break;
                default: throw new ArgumentException(id.ToString());
            }
            initPrototypeMethod(ITERATOR_TAG, id, s, arity);
        }


        public override Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
                                 Scriptable thisObj, Object[] args)
        {
            if (!f.hasTag(ITERATOR_TAG))
            {
                return base.execIdCall(f, cx, scope, thisObj, args);
            }
            int id = f.methodId();

            if (id == Id_constructor)
            {
                return jsConstructor(cx, scope, thisObj, args);
            }

            if (!(thisObj is NativeIterator))
                throw incompatibleCallError(f);

            NativeIterator iterator = (NativeIterator)thisObj;

            switch (id)
            {

                case Id_next:
                    return iterator.next(cx, scope);

                case Id___iterator__:

                    return thisObj;

                default:
                    throw new ArgumentException(id.ToString());
            }
        }


        private static Object jsConstructor(Context cx, Scriptable scope,
                                            Scriptable thisObj, Object[] args)
        {
            if (args.Length == 0 || args[0] == null ||
                args[0] == Undefined.instance)
            {
                throw ScriptRuntime.typeError1("msg.no.properties",
                                               ScriptRuntime.toString(args[0]));
            }
            Scriptable obj = ScriptRuntime.toObject(scope, args[0]);
            bool keyOnly = args.Length > 1 && ScriptRuntime.toBoolean(args[1]);
            if (thisObj != null)
            {

                IEnumerator iterator =
                    VMBridge.instance.getJavaIterator(cx, scope, obj);
                if (iterator != null)
                {
                    scope = ScriptableObject.getTopLevelScope(scope);
                    return cx.getWrapFactory().wrap(cx, scope,
                            new WrappedJavaIterator(iterator, scope),
                            typeof(WrappedJavaIterator));
                }


                Scriptable jsIterator = ScriptRuntime.toIterator(cx, scope, obj,
                                                                 keyOnly);
                if (jsIterator != null)
                {
                    return jsIterator;
                }
            }


            Object objectIterator = ScriptRuntime.enumInit(obj, cx,
                keyOnly ? ScriptRuntime.ENUMERATE_KEYS_NO_ITERATOR
                        : ScriptRuntime.ENUMERATE_ARRAY_NO_ITERATOR);
            ScriptRuntime.setEnumNumbers(objectIterator, true);
            NativeIterator result = new NativeIterator(objectIterator);
            result.setPrototype(NativeIterator.getClassPrototype(scope,
                                    result.getClassName()));
            result.setParentScope(scope);
            return result;
        }

        private Object next(Context cx, Scriptable scope)
        {
            bool b = ScriptRuntime.enumNext(this.objectIterator);
            if (!b)
            {

                throw new JavaScriptException(
                    NativeIterator.getStopIterationObject(scope), null, 0);
            }
            return ScriptRuntime.enumId(this.objectIterator, cx);
        }

        public class WrappedJavaIterator
        {
            public WrappedJavaIterator(IEnumerator iterator, Scriptable scope)
            {
                this.iterator = iterator;
                this.scope = scope;
            }

            public Object next()
            {
                if (!iterator.MoveNext())
                {
                    throw new JavaScriptException(
                        NativeIterator.getStopIterationObject(scope), null, 0);
                }
                return iterator.Current;
            }

            public Object __iterator__(bool b)
            {
                return this;
            }

            private IEnumerator iterator;
            private Scriptable scope;
        }


        public override int findPrototypeId(String s)
        {
            int id;

            id = 0; String X = null;
            int s_length = s.Length;
            if (s_length == 4) { X = "next"; id = Id_next; }
            else if (s_length == 11) { X = "constructor"; id = Id_constructor; }
            else if (s_length == 12) { X = "__iterator__"; id = Id___iterator__; }
            if (X != null && X != s && !(X == s)) id = 0;
            goto L0;

        L0: ;

            return id;
        }


    }
}
